<script setup lang="ts">
	import { useCorps } from "./utils/hook";
	import Refresh from "@iconify-icons/ep/refresh";
	import AddFill from "@iconify-icons/ri/add-circle-line";
  import More from "@iconify-icons/ep/more-filled";
	import { PureTableBar } from "@/components/RePureTableBar";
	import { useRenderIcon } from "@/components/ReIcon/src/hooks";
	import { ref } from "vue";
  import { message } from "@/utils/message";
  import { emitter } from "@/utils/mitt";
  import Printpage from "@/common/printpage.vue";
  import { deliveryOrderExportApi } from "@/api/purchaseOrderApi";
  import dayjs from "dayjs";
	const {
		form,
		loading,
		columns,
		dataList,
		pagination,
		isShow,
		onSearch,
		resetForm,
		openDialog,
		handleSizeChange,
		handleCurrentChange,
		deviceDetection,
		handleDelete,
    companySelect,
    customerSelect,
    sortChange,
    expandColumns
	} = useCorps();
	const formRef = ref();
  const orderTypeSelect = [
    { value: 1, label: '销售出库'},
    { value: 2, label: '生产领料'},
    { value: 3, label: '其他出库'},
    { value: 4, label: '采购退货'},
  ]
  const statusSelect = [
    { value: 1, label: '待执行'},
    { value: 2, label: '已执行'},
  ]
  const changJurictionFormData = (row, index) => {
    if(index === 1){
      let printcontrats = {
        printinfos: row,
        printinfoid: 9,
        printinfosstuas: true,
        componname: '',
      };
      emitter.emit("printinfos", printcontrats);
    } else {
      exportDeliveryOrder({
        deliveryOrderIds: [row.deliveryOrderId]
      })
    }

  }
  const multipleSelect = ref([]);
  const selectionChange = (val: any) => {

    multipleSelect.value = val;
  }
  const multipleExport = () => {
    if(multipleSelect.value.length > 0) {
      let arr = []
      for (let item of multipleSelect.value) {
        arr.push(item.deliveryOrderId)
      }
      exportDeliveryOrder({
        deliveryOrderIds: arr
      })
    } else {
      message('请选择要导出的数据', {
        type: "warning"
      });
    }
  }
  const exportDeliveryOrder = (params: any) => {
    deliveryOrderExportApi(params).then((res: any) => {
      const elink = document.createElement("a");
      elink.download = "出库单导出-" + dayjs().format('YYYYMMDDHHmmss') +".xls";
      elink.style.display = "none";
      const blob = new Blob([res], {
        type: "application/x-msdownload",
      });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    })
  }
  //合计
  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计';
        return;
      }
      const values = data.map(item => Number(item[column.property]));
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if(column.property === 'number') {
            return prev + curr;
          } else if(column.property === 'amount') {
            return prev + curr;
          } else {
            return '--'
          }
        }, 0);
        // sums[index] += '';
      } else {
        sums[index] = '--';
      }
    });
    return sums;
  };
</script>

<template>
	<div class="main">
		<el-form ref="formRef" :inline="true" :model="form"
			class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			<el-form-item label="出库单号:">
				<el-input v-model="form.orderNo" class="!w-[180px]" clearable placeholder="请输入" />
			</el-form-item>

      <el-form-item label="出库单日期:">
        <el-date-picker v-model="form.orderRangeDate" type="daterange" placeholder="请选择" clearable style="width: 280px" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item label="单据类型:">
        <el-select v-model="form.orderType" class="!w-[110px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in orderTypeSelect"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态:">
        <el-select v-model="form.status" class="!w-[100px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in statusSelect"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属公司:">
        <el-select v-model="form.companyId" class="!w-[180px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in companySelect"
            :key="item.companyId"
            :value="item.companyId"
            :label="item.companyName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户:">
        <el-select v-model="form.customerId" class="!w-[120px]" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in customerSelect"
            :key="item.customerId"
            :value="item.customerId"
            :label="item.name"
          />
        </el-select>

      </el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="useRenderIcon('ri:search-line')" :loading="loading" @click="onSearch">
					搜索
				</el-button>
				<el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
					重置
				</el-button>
			</el-form-item>
		</el-form>

		<div ref="contentRef" :class="['flex', deviceDetection() ? 'flex-wrap' : '']">
			<PureTableBar :class="[isShow && !deviceDetection() ? '!w-[60vw]' : 'w-full']"
				style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)" title=" " :columns="columns"
				@refresh="onSearch">
        <template #title>
          <el-button @click="multipleExport()">
          	批量导出
          </el-button>
        </template>
				<template #buttons>
          <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDialog()">
          	创建订单
          </el-button>

				</template>
				<template v-slot="{ size, dynamicColumns }">
					<pure-table ref="tableRef" showOverflowTooltip table-layout="auto"
						:loading="loading" :size="size" adaptive :adaptiveConfig="{ offsetBottom: 108 }"
						:data="dataList" :columns="dynamicColumns" :pagination="pagination" @sort-change="sortChange" @selection-change="selectionChange"
						:paginationSmall="size === 'small' ? true : false" :header-cell-style="{background: 'var(--el-fill-color-light)',
						color: 'var(--el-text-color-primary)'}" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
            <template #expand="props">
              <pure-table ref="tableRef" align-whole="center" showOverflowTooltip table-layout="auto" border :summary-method="getSummaries" show-summary
                :adaptiveConfig="{ offsetBottom: 108 }" :data="props.row.orderProducts" :columns="expandColumns"
                :paginationSmall="true" :header-cell-style="{background: '#e3e3e3', color: 'var(--el-text-color-primary)'}">

              </pure-table>
            </template>
            <template #statusName="{ row }">
              <el-tag type="warning" v-if="row.status === 1">{{row.statusName}}</el-tag>
              <el-tag type="success" v-if="row.status === 2">{{row.statusName}}</el-tag>
            </template>
						<template #operation="{ row }">
              <el-button class="reset-margin" link type="primary" :size="size" @click="openDialog('执行', row)" v-if="row.status === 1">
              	执行
              </el-button>
              <el-button link type="primary" @click="changJurictionFormData(row, 2)" v-if="row.status === 2">导出</el-button>
              <el-button link type="primary" @click="changJurictionFormData(row, 1)">打印</el-button>
              <el-button class="reset-margin" link type="primary" :size="size" @click="openDialog('订单详情', row)">
              	详情
              </el-button>
              <el-dropdown v-if="row.status === 1">
                <el-button
                  class="ml-3 mt-[2px]"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(More)"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openDialog('编辑订单', row)">
                      <el-button class="reset-margin" link type="primary" :size="size">
                      	编辑
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(row)">
                      <el-button class="reset-margin" link type="primary" :size="size">
                      	删除
                      </el-button>
                    </el-dropdown-item>


                  </el-dropdown-menu>
                </template>
              </el-dropdown>
						</template>
					</pure-table>
				</template>
			</PureTableBar>
		</div>
    <Printpage></Printpage>
	</div>
</template>

<style scoped lang="scss">
	.main-content {
		margin: 10px 10px 0 !important;
	}
</style>
